import React, { useEffect, useState } from 'react'
import { Row, Col, List, Card, Avatar, Drawer, Popover } from 'antd';
import { LinkOutlined, 
         EllipsisOutlined, 
         PieChartOutlined,
         BarChartOutlined,
       } from '@ant-design/icons';
import axios from 'axios';
import * as echarts from 'echarts';
import _ from 'lodash';
import './home.css'

const { Meta } = Card;
const content = (
  <div>
    <div className='linkdiv'><img style={{height:'1.3rem', width:'1.3rem'}} src='https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F016a8359a61d57a8012028a96b4610.jpg%401280w_1l_2o_100sh.jpg&refer=http%3A%2F%2Fimg.zcool.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1659861156&t=c2dbbce866eba89a7d8714c32cbc2900' alt='1'/> &emsp; <a href='https://www.bilibili.com/'><span style={{fontSize:'1.1rem'}}>B站</span></a></div>
    <div className='linkdiv'><img style={{height:'1.3rem', width:'1.3rem'}} src='https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fi-1.xdowns.com%2F2020%2F2%2F14%2Fa139f4ca-c2a3-4d94-a3b0-e793df1ca409.png&refer=http%3A%2F%2Fi-1.xdowns.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1659861223&t=6b2d42418d3414041fadca7b44821c51' alt='2'/> &emsp; <a href='https://news.cctv.com/'><span style={{fontSize:'1.1rem'}}>央视新闻</span></a></div>
    <div className='linkdiv'><img style={{height:'1.3rem', width:'1.3rem'}} src='https://img1.baidu.com/it/u=3571765666,3962800901&fm=253&fmt=auto&app=138&f=JPEG?w=256&h=256' alt='3'/> &emsp; <a href='https://www.ifeng.com/'><span style={{fontSize:'1.1rem'}}>凤凰网</span></a></div>
    <div className='linkdiv'><img style={{height:'1.3rem', width:'1.3rem'}} src='https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg1.shop.10086.cn%2Fgoods%2Fta8y699nt8kttqmb6_700x700.png&refer=http%3A%2F%2Fimg1.shop.10086.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1659861899&t=c034bd2eab841963043ca731fb3694a9' alt='5'/> &emsp; <a href='https://www.miguvideo.com/mgs/website/prd/sportsHomePage.html'><span style={{fontSize:'1.1rem'}}>咪咕体育</span></a></div>
    <div className='linkdiv'><img style={{height:'1.3rem', width:'1.3rem'}} src='https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.ppcn.net%2Fuploadfile%2F2021%2F1109%2F20211109050616227.png&refer=http%3A%2F%2Fimg.ppcn.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1659861939&t=f503e0d0df0cc321184828af95c356e2' alt='6'/> &emsp; <a href='https://military.china.com/'><span style={{fontSize:'1.1rem'}}>中华军事网</span></a></div>
  </div>
);
const content2 = (
  <h3><b>未完待续......</b></h3>
)

export default function Home() {
  const [viewList, setViewList] = useState([]);
  const [starList, setStarList] = useState([]);
  const [visible, setVisible] = useState(false);
  const [pieChart, setPieChart] = useState(null);
  const [pieDataList, setPieDataList] = useState([]);
  const { username, region, role:{roleName}} = JSON.parse(localStorage.getItem('token'));
  useEffect(()=>{
    Promise.all([
      axios.get('/news?auditState=2&_expand=category&_sort=view&_order=desc&_limit=6'),
      axios.get('/news?auditState=2&_expand=category&_sort=star&_order=desc&_limit=6'),
      axios.get('/news?publishState=2&_expand=category')
    ]).then(res =>{
      setViewList(res[0].data);
      setStarList(res[1].data);
      eColumnChart(_.groupBy(res[2].data, item => item.category.title));  //按照item.category,title进行分类成object
      // eslint-disable-next-line eqeqeq
      setPieDataList(res[2].data.filter(item => item.author == username));
    })
    return (()=>{
      window.onresize = null;
    })
  },[username])

  const ePieChart = () => {   //饼状图渲染
    let nowList = _.groupBy(pieDataList, item => item.category.title);
    let list = []; 
    for(var key in nowList){
      list.push({
        name: key,
        value: nowList[key].length
      })
    }
    var myChart;
    if(!pieChart){
      myChart = echarts.init(document.getElementById('piechart'));
      setPieChart(myChart);
    }
    else{
      myChart = pieChart;
    }

    myChart.setOption({
      title: {
        text: '个人新闻分类',
        subtext: '饼状图',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: 'Access From',
          type: 'pie',
          radius: '50%',
          data: list,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    });
  }

  const eColumnChart = (obj) => {    //柱状图渲染
    let myChart = echarts.init(document.getElementById('columnchart'));
    myChart.setOption({
      title: {
        text: '新闻分类图示'
      },
      legend:{
        data: ['数量']
      },
      tooltip:{},
      xAxis: {
        data: Object.keys(obj),  //Object.keys以数组形式输出obj的key
        axisLabel:{
          rotate:'45',
          interval:'0'
        }
      },
      yAxis: {
        minInterval: 1,
      },
      series: [
        {
          name: '数量',
          type: 'bar',
          data: Object.values(obj).map(item => item.length)   //Object.values以数组形式输出obj的values
        }
      ]
    });
    window.onresize = ()=>{
        myChart.resize();  //让eChart适应窗口大小
    }
  }

  const closeDrawer = () =>{
    setVisible(false);
  }
  return (
    <div>
      <Row>
        <Col xs={{ span: 5, offset: 1 }}>
          <List
            size="large"
            header={<h2>用户最常浏览&emsp;<BarChartOutlined /></h2>}
            bordered
            dataSource={viewList}
            renderItem={item => <List.Item><a href={`/sandbox/news/preview/${item.id}`}>{item.title}</a></List.Item>}
          />
        </Col>
        <Col xs={{ span: 11, offset: 1 }} lg={{ span: 6, offset: 2 }}>
          <List
            size="large"
            header={<h2>用户点赞最多&emsp;<BarChartOutlined /></h2>}
            bordered
            dataSource={starList}
            renderItem={item => <List.Item><a href={`/sandbox/news/preview/${item.id}`}>{item.title}</a></List.Item>}
          />
        </Col>
        <Col xs={{ span: 5, offset: 1 }} lg={{ span: 6, offset: 2 }}>
          <Card
            cover={
              <img
                alt="example"
                src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F202006%2F22%2F20200622105855_lqhmv.thumb.1000_0.gif&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1659755500&t=bab1cea4a4067b9a9a064e499e846ce4"
              />
            }
            actions={[
              <PieChartOutlined key="pieChart" onClick={()=>{
                setVisible(true);
                setTimeout(()=>{
                  ePieChart();
                },0)}
              }/>,
              <Popover content={content} title={<h2><b>外部链接</b></h2>}>
                <LinkOutlined key="edit" />
              </Popover>,
              <Popover content={content2}>
              <EllipsisOutlined key="ellipsis" />
              </Popover>
            ]}
          >
            <Meta
              avatar={<Avatar src="https://joeschmoe.io/api/v1/random" />}
              title={username}
              description={<div><b>{region?region:'全球'}</b> &emsp; {roleName}</div>}
            />
          </Card>
        </Col>
      </Row>
      <Drawer 
          placement="right" 
          width="31rem"
          closable={true}
          onClose={closeDrawer} 
          visible={visible}>
          <div id='piechart' style={{height:'30rem', width:'100%'}}></div>
      </Drawer>
      <div id='columnchart' style={{height:'20rem', width:'100%', marginTop:'6rem'}}></div>
    </div>
  )
}
